<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <script src="aliyun-sdk.min.js"></script>
  <script src="vod-sdk-upload-1.0.7.min.js"></script>
</head>

<body>
  OSS上传配置
  <hr />
  <table frame=void width="400px">
    <tr>
      <td>应用鉴权http地址:</td>
      <td><input type="text" id="httpServer" size="40" value="http://192.168.2.153:8080/aliyun/sts"> </td>
      <td><button type="button" onclick="init()">刷新</button></td>


    </tr>
    <tr>
      <td> endpoint:</td>
      <td><input type="text" id="endpoint" size="40" value="http://oss-cn-hangzhou.aliyuncs.com"></td>
      <td> bucket:</td>
      <td><input type="text" id="bucket" size="20" value="chuandao-in1"></td>
    </tr>
    <tr>
      <td> object前缀:</td>
      <td><input type="text" id="objectPre" size="20" value="1001/201803/"></td>
    </tr>
  </table>
  <hr /> 文件管理
  <hr />
  <input type="file" name="file" id="files" multiple/>
  <button type="button" onclick="deleteFile()">删除文件</button>
  <input type="text" id="deleteIndex" size="3" value="0">
  <button type="button" onclick="cancelFile()">取消文件</button>
  <input type="text" id="cancelIndex" size="3" value="0">

  <button type="button" onclick="resumeFile()">恢复文件</button>
  <input type="text" id="resumeIndex" size="3" value="0">

  <hr /> 列表管理
  <hr />
  <button type="button" onclick="getList()">获取上传列表</button>
  <button type="button" onclick="clearList()">清理上传列表</button>
  <hr /> 上传管理
  <hr/>
  <button type="button" onclick="start()">开始上传</button>
  <button type="button" onclick="stop()">停止上传</button>
  <hr />
  <select multiple="multiple" id="textarea" style="position:relative; width:620px; height:450px; vertical-align:top; border:1px solid #cccccc;"></select>
  <button type="button" onclick="clearLog()">清日志</button>

  <script>
    var uploader = null;

    function init() {
      uploader = new VODUpload({
        // 文件上传失败
        'onUploadFailed': function(uploadInfo, code, message) {
          log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
        },
        // 文件上传完成
        'onUploadSucceed': function(uploadInfo) {
          console.log(uploadInfo);
          log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        },
        // 文件上传进度
        'onUploadProgress': function(uploadInfo, totalSize, uploadedSize) {
          log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(uploadedSize * 100 / totalSize) + "%");
        },
        // STS临时账号会过期，过期时触发函数
        'onUploadTokenExpired': function(uploadInfo) {
          log("onUploadTokenExpired");
          // 实现时，从新获取STS临时账号用于恢复上传
          stsToken = httpGet(httpServer, callback);
          uploader.resumeUploadWithToken(stsToken.AccessKeyId, stsToken.AccessKeySecret, stsToken.SecurityToken, stsToken.Expiration);
        },
        // 开始上传
        'onUploadstarted': function(uploadInfo) {
          log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        }
      });

    //   var httpServer = document.getElementById("httpServer").value;
    //   result = httpGet(httpServer);
    //   stsToken = JSON.parse(result);

    //   if (null == stsToken || stsToken.status != 200) {
    //     alert("服务端请求STS失败");
    //     return;
    //   }
      // OSS直接上传:STS方式，安全但是较为复杂，建议生产环境下使用。
      // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
      uploader.init("STS.Ezd2bssZK9VjQETNobJqCb9Si", "8WZ2njaKao4wxxd1oM9GT5A2xLZJtiSUkm9qkh7SUch2", "CAIS7gF1q6Ft5B2yfSjIpLnRedjHnoVqjpSBU2Plqm83Rv5vjfz4izz2IHlNeHRvBesdsf82mG1U7PgdlqN2RpNETHvZdsZqtkvjVNluJ9ivgde8yJBZor/HcDHhJnyW9cvWZPqDP7G5U/yxalfCuzZuyL/hD1uLVECkNpv74vwOLK5gPG+CYCFBGc1dKyZ7tcYeLgGxD/u2NQPwiWeiZygB+CgE0Dgmtvjlm53EtUeC0QKnk9V4/dqhfsKWCOB3J4p6XtuP2+h7S7HMyiY46WIRrf4q0fMYomyY5YjBXgULvUqcXu/Z/txmPPDK4BbQtW0uGoABQEArM5PqVE35Iarew43VWmCLWsmtfiHHVhOOtlcFR/xzUFcH8ZCa78rsh05Sd78torJ0mf1sIwZzpJ/5MBzJGmTTj4GkDcN+SlvXOKMdCYDTPamjQLUnvlC44JkSUR6A+ENcHkg5+6CbwdmbAmP11SeYHEaRGW2goVs0HETw6jA=", "2018-03-30T09:53:21Z");
    }

    document.getElementById("files")
      .addEventListener('change', function(event) {
        if (null === uploader) {
          init();
        }

        var endpoint = document.getElementById("endpoint").value;
        var bucket = document.getElementById("bucket").value;
        var objectPre = document.getElementById("objectPre").value;
        var userData = '{"Vod":{"Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19",\
                "Tags":"tag1,tag2,标签3","UserData":"user data"}}';

        for (var i = 0; i < event.target.files.length; i++) {
          log("add file: " + event.target.files[i].name);
          uploader.addFile(event.target.files[i], endpoint, bucket, objectPre + event.target.files[i].name, userData);
        }
      });

    var textarea = document.getElementById("textarea");

    function callback(str) {
      stsToken = JSON.parse(str);
      if (stsToken.status != 200) {
        alert("服务端请求STS失败");
        return;
      }
      // OSS直接上传:STS方式，安全但是较为复杂，建议生产环境下使用。
      // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
      uploader.init(stsToken.AccessKeyId, stsToken.AccessKeySecret, stsToken.SecurityToken, stsToken.Expiration);
    }

    function start() {
      log("start upload.");
      uploader.startUpload();
    }

    function stop() {
      log("stop upload.");
      uploader.stopUpload();
    }

    function resumeWithToken() {
      log("resume upload with token.");
      var uploadAuth = document.getElementById("uploadAuth").value;

      var accessKeyId = document.getElementById("accessKeyId").value;
      var accessKeySecret = document.getElementById("accessKeySecret").value;
      var secretToken = document.getElementById("secretToken").value;
      var expireTime = document.getElementById("expireTime").value;

      uploader.resumeUploadWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
    }

    function clearList() {
      log("clean upload list.");
      uploader.cleanList();
    }

    function getList() {
      log("get upload list.");
      var list = uploader.listFiles();
      for (var i = 0; i < list.length; i++) {
        log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
      }
    }

    function deleteFile() {
      if (document.getElementById("deleteIndex").value) {
        var index = document.getElementById("deleteIndex").value
        log("delete file index:" + index);
        uploader.deleteFile(index);
      }
    }

    function cancelFile() {
      if (document.getElementById("cancelIndex").value) {
        var index = document.getElementById("cancelIndex").value
        log("cancel file index:" + index);
        uploader.cancelFile(index);
      }
    }

    function resumeFile() {
      if (document.getElementById("resumeIndex").value) {
        var index = document.getElementById("resumeIndex").value
        log("resume file index:" + index);
        uploader.resumeFile(index);
      }
    }

    function clearLog() {
      textarea.options.length = 0;
    }

    function log(value) {
      if (!value) {
        return;
      }

      var len = textarea.options.length;
      if (len > 0 && textarea.options[len - 1].value.substring(0, 40) == value.substring(0, 40)) {
        textarea.remove(len - 1);
      } else if (len > 25) {
        textarea.remove(0);
      }

      var option = document.createElement("option");
      option.value = value, option.innerHTML = value;
      textarea.appendChild(option);
    }

    function httpGetAsync(url, callback) {
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
          callback(xmlHttp.responseText);
      }
      xmlHttp.open("GET", url, true); // true for asynchronous
      xmlHttp.send(null);
    }

    function httpGet(url) {
    //   var xmlHttp = new XMLHttpRequest();
    //   xmlHttp.open("GET", url); // false for synchronous request
    //   xmlHttp.send(null);
      return "";
    }
  </script>

</body>

</html>